package com.elitel;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class NashornExample22 {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        try {
            // 定义JavaScript转换函数，解析JSON并返回修改后的对象
            String fullJsCode = "function transform(jsonStr) {" +
                    "  var obj = JSON.parse(jsonStr);" +
                    "  obj.city = \"bk\";" +
                    "  return JSON.stringify(obj);" +
                    "}";

            engine.eval(fullJsCode);

            // 传入JSON字符串
            String inputJson = "{\"name\":\"pop\",\"age\":5}";
            engine.put("input", inputJson);

            // 执行函数并获取结果
            String resultJson = (String) engine.eval("transform(input)");

            System.out.println(resultJson);
            // 输出: {"name":"pop","age":5,"city":"bk"}

        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}